#!/usr/local/bin/php
<?php
ob_get_level() && ob_clean();

/**
 * Скрипт создает конфиг для индексирования материалов системой Sphinx
 *
 * Вродные параметры:
 *
 * 1) Путь к env.php, если не указан, используется стандартный путь
 *    [project]/application/configs/env.php
 *
 * 2) Путь для сохранения конфига, если не указан, то вместо сохранения
 *    содержимое конфига будет отправлено в выходной поток, если значение 1,
 *    то скрипт создаст файл sphinx.conf в текущей папке.
 *
 * Пример:
 *
 *    /path/sphinx.php 0 1 - создаст файл /path/sphinx.conf
 *
 *    /path/sphinx.php /path/to/env.php /path/to/config.conf
 *
 *    /path/sphinx.php - выводит содержимое конфига
 */

$envPath = isset($argv[1]) ? $argv[1] : null;

if (!$envPath) {
    $i = 20;
    $dir = __FILE__;
    while ($i-- > 0) {
        $dir = dirname($dir);
        if (basename($dir) == 'application') {
            $envPath = implode(DIRECTORY_SEPARATOR, array($dir, 'configs', 'env.php'));
            break;
        }
    }
}

if (!file_exists($envPath)) {
    die('Config file does not exists');
}

include $envPath;

set_include_path(INCLUDE_PATH);
error_reporting(ERROR_LEVEL);

include 'phplib.php';

$savePath = isset($argv[2]) ? $argv[2] : null;

if ($savePath) {
    if ($savePath == 1) {
        $savePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . basename(__FILE__, '.php') . '.conf';
    } elseif (!file_exists(dirname($savePath))) {
        die('Config save path does not exists');
    }
}

$config = include APPLICATION_PATH.'/configs/application.php';

$indexPath = rtrim($config['sphinx_data_path'], DIRECTORY_SEPARATOR);

ob_start();

?>

source src_materials
{
    type			= mysql

	sql_host		= <?= $config['resources']['db']['params']['host']."\n" ?>
	sql_user		= <?= $config['resources']['db']['params']['username']."\n" ?>
	sql_pass		= <?= $config['resources']['db']['params']['password']."\n" ?>
	sql_db			= <?= $config['resources']['db']['params']['dbname']."\n" ?>
	sql_port		= 3306

    sql_query_pre = SET NAMES utf8
    sql_query_pre = REPLACE INTO t_sphinx_updater VALUES('materials', NOW())

    sql_query = SELECT  material_id as id, \
                        title, \
                        content, \
                        UNIX_TIMESTAMP(created) AS created, \
                        category_id, \
                        status as active \
                FROM \
                        t_material_search_content \
                WHERE   updated <= (select last_update FROM t_sphinx_updater WHERE search_index = 'materials') \
                        AND \
                        status > 0  

    sql_attr_uint		= category_id
    sql_attr_uint		= active
	sql_attr_timestamp	= created

    sql_query_info		= SELECT * FROM t_material_search_content WHERE material_id=$id
}

source src_materials_delta : src_materials
{
    sql_query_pre = SET NAMES utf8
    sql_query = SELECT  material_id as id, \
                        title, \
                        content, \
                        UNIX_TIMESTAMP(created) AS created, \
                        category_id, \
                        status as active \
                FROM \
                        t_material_search_content \
                WHERE   updated > (select last_update FROM t_sphinx_updater WHERE search_index = 'materials') 

}

index i_materials
{
	source			= src_materials
	path			= <?= $indexPath ?>/materials
	docinfo			= extern
	charset_type    = utf-8
    morphology      = stem_enru, soundex, metaphone
    min_stemming_len = 4
}

index i_materials_delta : i_materials
{
	source			= src_materials_delta
	path			= <?= $indexPath ?>/materials_delta
	docinfo			= extern
	charset_type    = utf-8
    morphology      = stem_enru, soundex, metaphone
    min_stemming_len = 4
}

<?php

$content = ob_get_clean();

if ($savePath) {
    file_put_contents($savePath, $content, LOCK_EX);
} else {
    echo $content;
}

